package com.ruoyi.web.controller.system;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.tree.PostTreeNode;
import com.ruoyi.system.domain.tree.TreeNode;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.util.PostTreeBuild;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门信息
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {

    private final ISysDeptService deptService;

    private final SysPostMapper sysPostMapper;

    /**
     * 获取部门列表
     */
    @GetMapping("/list")
    public R<List<SysDept>> list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return R.ok(depts);
    }

    /**
     * 获取部门列表
     */
    @GetMapping("/tableListTree")
    public R<List<TreeNode>> tableListTree(SysDept dept) {
        return R.ok(deptService.deptControlTree(dept));
    }


    /**
     * 获取部门列表
     */
    @GetMapping("/deptPostTree")
    public R<List<PostTreeNode>> deptPostTree(SysDept dept) {
        // 查询所有部门
        List<SysDept> deptLists = deptService.selectAll();

        // 查询所有2级岗位
        List<SysPost> postTows = sysPostMapper.selectList(new QueryWrapper<SysPost>()
            .eq("remark", 2).eq("status", 0));
        Map<Long, List<PostTreeNode>> map = new HashMap<>();
        for (SysPost sysPost : postTows) {
            List<PostTreeNode> posts = map.get(sysPost.getSuperiorsId());
            if (posts == null) {
                posts = new ArrayList<>();
            }
            PostTreeNode postTreeNode = new PostTreeNode(sysPost.getPostId(), "二级角色", sysPost.getSuperiorsId(), sysPost.getPostName(), 1, 2);
            posts.add(postTreeNode);
            map.put(sysPost.getSuperiorsId(), posts);
        }
        // 查询所有1级岗位
        List<SysPost> postOnes = sysPostMapper.selectList(new QueryWrapper<SysPost>()
            .eq("remark", 1).eq("status", 0));
        // 根据2级岗位挂在1级岗位下级 同时根据 部门进行归类岗位
        Map<Long, List<PostTreeNode>> postMaps = new HashMap<>();
        for (SysPost sysPost : postOnes) {
            sysPost.setChildren(map.get(sysPost.getPostId()));
            List<PostTreeNode> posts = postMaps.get(sysPost.getDeptId());
            if (posts == null) {
                posts = new ArrayList<>();
            }
            PostTreeNode postTreeNode = new PostTreeNode(sysPost.getPostId(), "一级角色", sysPost.getSuperiorsId(), sysPost.getPostName(), 1, 1);
            postTreeNode.setChildren(sysPost.getChildren());
            posts.add(postTreeNode);
            postMaps.put(sysPost.getDeptId(), posts);
        }
        // 将所有岗位挂在部门名下
        // 将部门上下级区分
        List<PostTreeNode> treeNodeList = Lists.newArrayList();
        for (SysDept sysDept : deptLists) {
            PostTreeNode postTreeNode = new PostTreeNode(sysDept.getDeptId(), "部门", sysDept.getParentId(), sysDept.getDeptName(), 0, 0);
            postTreeNode.setChildren(postMaps.get(sysDept.getDeptId()));
            treeNodeList.add(postTreeNode);
        }

        // 创建树形结构（数据集合作为参数）
        PostTreeBuild treeBuild = new PostTreeBuild(treeNodeList);
        // 原查询结果转换树形结构
        treeNodeList = treeBuild.buildTree();
        return R.ok("操作成功", treeNodeList);
    }

    /**
     * 部门节点塞入岗位
     *
     * @param list
     * @param map
     */
    private void setData(List<TreeNode> list, Map<Long, List<SysPost>> map) {
        for (TreeNode treeNode : list) {
            List<SysPost> sysPosts = map.get(treeNode.getDeptId());
            List<TreeNode> treeNodeList = (treeNode.getChildren() == null ? new ArrayList<>() : treeNode.getChildren());
            if (!treeNodeList.isEmpty()) {
                setData(treeNodeList, map);
            }
            if (sysPosts == null || sysPosts.isEmpty()) {
                continue;
            }
            for (SysPost post : sysPosts) {

                SysDept sysDept = new SysDept();
                sysDept.setDeptId(post.getPostId());
                sysDept.setDeptName(post.getPostName());
                TreeNode node = new TreeNode(post.getPostId(), post.getPostId(), treeNode.getDeptId(), post.getPostName(), sysDept, 100);
                treeNodeList.add(node);
                treeNode.setChildren(treeNodeList);
            }
        }
    }

    /**
     * 查询部门列表（排除节点）
     *
     * @param deptId 部门ID
     */
    @GetMapping("/list/exclude/{deptId}")
    public R<List<SysDept>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().equals(deptId) || StringUtils.splitList(d.getAncestors()).contains(Convert.toStr(deptId)));
        return R.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     *
     * @param deptId 部门ID
     */
    @GetMapping(value = "/{deptId}")
    public R<SysDept> getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return R.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody SysDept dept) {

        deptService.insertDept(dept);
        return toAjax(true);
    }

    /**
     * 修改部门
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody SysDept dept) {
        deptService.updateDept(dept);
        return toAjax(true);
    }

    /**
     * 删除部门
     *
     * @param deptId 部门ID
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public R<Void> remove(@PathVariable Long deptId) {

        deptService.deleteDeptById(deptId);

        return toAjax(true);
    }


    /**
     * 获取部门列表
     */
    @GetMapping("/tableListTreeDisposition")
    public R<List<TreeNode>> tableListTreeDisposition(SysDept dept) {
        List<TreeNode> list = deptService.deptControlTree(dept);
        setTreeValue(list);
        return R.ok(list);
    }

    private void setTreeValue(List<TreeNode> list) {
        for (TreeNode treeNode : list) {
            //            List<LcConfigurationVo> lcConfigurationVos = lcConfigurationMapper.getLists(treeNode.getDeptId());
            //            if (!lcConfigurationVos.isEmpty()) {
            //                if (lcConfigurationVos.size() == 3) {
            //                    treeNode.setIsDisposition(1);
            //                } else {
            //                    treeNode.setIsDisposition(2);
            //                }
            //            } else {
            //                treeNode.setIsDisposition(0);
            //            }
            //            if (treeNode.getChildren() != null) {
            //                setTreeValue(treeNode.getChildren());
            //            }
        }
    }
}
